package BinarySearch.Medium;

public class LC0875 {
    public int minEatingSpeed(int[] piles, int h) {
        int length = piles.length, maxPile = -1;
        for (int i = 0; i < length; i++) {
            maxPile = Math.max(maxPile, piles[i]);
        }

        int left = 1, right = maxPile + 1, mid;
        int lastValidK = -1;
        while (left < right) {
            mid = (left + right) / 2;
            // 检查当前取值是否符合要求
            int nHoursNeeded = 0;
            for (int i = 0; i < length; i++) {
                nHoursNeeded += (piles[i] + mid - 1) / mid; // 向上取整，在同样渐近复杂度的实现中，采用这种写法代替ceil可以显著减少运行时间
            }
            if (nHoursNeeded <= h) {
                lastValidK = mid;
                right = mid;
            }
            else {
                left = mid + 1;
            }
        }

        return lastValidK;
    }
}
